import api from '../../../api/index';
import dayjs from '../../../plugin/dayjs/index';
import daysbefore from '../../../plugin/daysbefore';
import * as echarts from '../../../components/ec-canvas/echarts';

//全局声明chart
var seriesDataArr1 = [];
var timeArr1 = [];
var chartPr = null;

// 时间格式化
function formatTime(date = new Date()) {
	return dayjs(date).format('YYYY-MM-DD HH:mm:ss');
}
function formatTime2(date = new Date()) {
	return dayjs(date).format('YYYY-MM-DD');
}
Page({
	/**
   * 页面的初始数据
   */
	data: {
		tab: {
			show2: false,
			active: 0,
			list: [
				{
					name: '高血压',
					id: '',
					index: 0,
					text:'1'
				},
				{
					name: '糖尿病',
					id: '',
					index: 1,
					text:'2'
				}
			],
		},
		inputshow2: false,
		inputlist2: [
			{ unit: 'mmol/L', value: '', text: '请输入血糖' },
		],
		c_val: 80,
		shebeiicon: 'https://hxhealth.oss-cn-beijing.aliyuncs.com/redstart/sportsAdministration/xueya.png',
		fasleshebeiicon: 'https://hxhealth.oss-cn-beijing.aliyuncs.com/redstart/sportsAdministration/gantanhao.png',
		xtValue: '',
		upValue: '',
		downValue: '',
		linedata: null,
		show: false,
		showec1: true,
		ec1: {
			// 初始化图表
			onInit: (canvas, width, height) => {
				//初始化echarts元素，绑定到全局变量，方便更改数据
				chartPr = echarts.init(canvas, null, {
					width: width,
					height: height
				});
				canvas.setChart(chartPr);
				return chartPr;
			}
    },
	},

	/**
   * 生命周期函数--监听页面加载
   */
	onLoad(options) {
		// this.drawProgress()
		
		this.getloadlist(); //查询当前最新数据
	},
	handlerTab(e) {
		console.log(e);
		const list = this.data.tab.list
		const index = e.currentTarget.dataset.index
		// const ids = e.currentTarget.dataset.item.id
		// this.getload(ids)
		this.setData({
		  'tab.active': index
		})
		this.gethistrorylist(); //查看历史数据
	
	},
	gethistrorylist() {
		api
			.post('/api/hxhealth/exams/records', {
				data: {
					begindate: daysbefore.daysbefore(7),
					enddate: formatTime2(),
					everyday: true,
					itemcode: 'XYZBXY001008',
					typecode: 'glucosemeter',
					everyday: true
				}
			})
			.then((res) => {
				// console.log(res);
				console.log('----历史数据----', res);
				if (res.length > 0) {
					const jsonData = res;
					// 提取数据的数组
					const values = [];
					const times = [];

					// 遍历 body 数组
					jsonData.forEach((entry) => {
						// 遍历 devices 数组
						entry.devices.forEach((device) => {
							console.log(device);
							// 找到 code 为 "XYZBXY001008" 的项
							const item = device.items.find((item) => item.code === 'XYZBXY001008');

							// 如果找到了，将 value 和 time 添加到相应的数组中
							if (item) {
								console.log(item);
								values.push(Number(item.value)); // 将值转换为数字类型
								times.push(entry.time.slice(0, 10).replace(/-/g, '/'));
							}
						});
					});
					const linedata = {
						values,
						times
					};
					console.log(linedata);
					this.setData({
						linedata
					});
					// 模拟获取接口数据
					setTimeout(() => {
						this.getEchartData(linedata);
					}, 1000);
				}
			});

	},
	// gethistrorylist() {
	// 	console.log('chakan----------------');
	// 	const linedata = {
	// 		values: [0],
	// 		times: ["2024/01/24"]
	// 	};
	// 	console.log(linedata);
	// 	this.setData({
	// 		linedata
	// 	});
	// 	// 模拟获取接口数据
	// 	setTimeout(() => {
	// 		this.getEchartData(linedata);
	// 	}, 1000);
	// },
	getloadlist() {
		// 整体列表查询
		api
			.post('/api/exams/lastvalues', {
				data: {
					devkind: 'glucosemeter',
					devmode: '',
					itemcode: '',
					typecode: '',
					unionuser: true
				}
			})
			.then((res) => {
				console.log(res);
				console.log('----最新数据----', res);
				const array = res;
				for (let y = 0; y < array.length; y++) {
					if (array[y].code == 'XYZBXY001008') {
						this.setData({
							xtValue: parseFloat(array[y].value).toFixed(1)
						});
					}
				}
			});
	},
	savedevices() {
		console.log('2222');
		let data = {
			name: '血糖监测',
			time: formatTime(),
			typecode: 'glucosemeter',
			typename: '血糖监测',
			devices: [
				{
					name: '血糖监测',
					kind: 'glucosemeter',
					items: [
						{
							code: 'XYZBXY001008',
							checkDate: null,
							level: null,
							value: this.data.inputlist2[0].value,
							deviceBrand: '',
							deviceNo: ''
						}
					]
				}
			]
		};
		// 整体列表查询
		api
			.post('/api/hxhealth/exams/save', {
				data
			})
			.then((res) => {
				// console.log(res);
				console.log('----保存录入----', res);
				this.getloadlist();
				this.closesaveNickname();
				wx.showToast({
					icon: 'none',
					title: '保存成功'
				});
			})
			.catch((e) => {
				console.log(e);
				wx.showToast({
					icon: 'none',
					title: e.faultstring ? e.faultstring : '保存失败'
				});
			});
	},
	openNickname2() {
		this.setData({
			inputshow2: true
		});
	},
	closesaveNickname() {
		this.setData({
			inputshow2: false
		});
	},
	userNameInput2(e) {
		console.log(e.detail.value);
		this.setData({
			'inputlist2[0].value': e.detail.value
		});
	},
	saveNickname() {
		console.log(this.data.inputlist2);
		this.savedevices();
	},
	modal_click_Hidden() {
		this.setData({
			inputshow2: false
		});
	},
	getEchartData(linedata) {
		console.log(linedata);
		seriesDataArr1 = [
			{
				name: '血糖变化趋势',
        type: 'line',
        symbol: 'none',
				stack: 'Total',
				smooth: true,
        data: linedata.values,
        lineStyle: {
          width: 1,
          shadowColor: 'rgba(0,0,0,0.1)',
          shadowBlur: 10,
          shadowOffsetY: 8
        },
			}
    ];
		timeArr1 = linedata.times
		console.log(seriesDataArr1);
		this.runColumncCanva1();
	},
	// 绘制图表
	runColumncCanva1() {
		console.log(seriesDataArr1);
    console.log(timeArr1);
	var option = {
		title: {
			// text: '次/分',
			textStyle: {
				fontSize: 9,
				color: '#666666'
			}
		},
		color: [ '#37A2DA' ],
		legend: {
			data: [ '血糖变化趋势'],
			icon: 'circle',
			left: 0,
			itemWidth: 9,
			// itemStyle: {
			//     color: '#5BBF70'
			// },
			textStyle: {
				color: '#333333',
				fontSize: 13
			}
		},
		grid: {
			left: '0%',
			right: '5%',
			bottom: 0,
			top: '15%',
			containLabel: true,
			show: true
		},
		tooltip: {
			show: true,
			trigger: 'axis'
		},
		xAxis: {
			type: 'category',
			boundaryGap: false,
			data: timeArr1,
			axisLabel: {
				fontSize: 12,
				rotate: 0 //倾斜度 -90 至 90 默认为0
			}
		},
		yAxis: {
			type: 'value',
			splitLine: {
				lineStyle: {
					type: 'dashed'
				}
			},
			axisLabel: {
				fontSize: 12
			}
		},
      series: seriesDataArr1
		};
    //这里一定要做个charts是否存在的判断，因为万一ec那里没有初始化，这里就会报错
    console.log(chartPr);
    if (chartPr) {
      chartPr.setOption(option);
		}
	},
	openkp() {
		wx.navigateTo({
			url: `/blood/pages/tnb-bzkp/index`,
		  })
	   },
	   openKy() {
		wx.navigateTo({
			url: `/blood/pages/ktfa/index`,
		  })
		},
	
	// 链接设备
	goBindEq() {
		wx.navigateTo({
			url: '/bracelet/pages/home/index'
		});
	},

	/**
   * 生命周期函数--监听页面初次渲染完成
   */
	onReady: function() {},

	/**
   * 生命周期函数--监听页面显示
   */
	onShow() {},

	/**
   * 生命周期函数--监听页面隐藏
   */
	onHide() {},

	/**
   * 生命周期函数--监听页面卸载
   */
	onUnload() {},

	/**
   * 页面相关事件处理函数--监听用户下拉动作
   */
	onPullDownRefresh() {},

	/**
   * 页面上拉触底事件的处理函数
   */
	onReachBottom() {},

	/**
   * 用户点击右上角分享
   */
	onShareAppMessage() {}
});
